package com.nova.android.tvlauncher.ui.view

import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.view.isVisible
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.databinding.ViewMainTopLeftAtvBinding
import com.nova.android.tvlauncher.ui.activity.atv.SearchAtvActivity
import com_github_lib_base.currentActivity
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.startKtxActivity


class MainTopLeftAtvView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    // 初始化视图
    private var binding: ViewMainTopLeftAtvBinding =
        ViewMainTopLeftAtvBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        // 允许子视图超出边界，以支持缩放动画
        clipChildren = false
        clipToPadding = false
        setupListeners()
    }

    fun mainTopLeftBinding() = binding

    fun setVoiceFocus(isFocus:Boolean){
        binding.tvVoice.isFocusable = isFocus
        binding.tvVoice.isFocusableInTouchMode = isFocus
    }

    private fun setupListeners() {
        val isShowVoice = AppCache.configLocalDto?.isShowVoiceIcon != false
        binding.tvVoice.setOnFocusChangeListener { view, b ->
            if (b) {

                binding.tvSearch.isVisible = false
                binding.tvKeyboard.isVisible = true

            } else {
                if(binding.tvKeyboard.isFocused==false){

                    binding.tvSearch.isVisible = true
                    binding.tvKeyboard.isVisible = false
                }

            }
        }



        binding.tvKeyboard.setOnFocusChangeListener { view, b ->
            if(binding.tvVoice.isFocused==false&&binding.tvKeyboard.isFocused==false){
                if (isShowVoice){
                    binding.tvSearch.isVisible = true
                    binding.tvKeyboard.isVisible = false
                }

            }

        }

        binding.tvKeyboard.clickNoRepeat {
            currentActivity?.let {
                it.startKtxActivity<SearchAtvActivity>()
            }
        }

        binding.tvVoice.clickNoRepeat {
            currentActivity?.let {
                startAssist(it)
            }
        }

    }

    private fun startAssist(context: Context) {
        try {
            val intent = Intent("android.intent.action.ASSIST")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) // 对应 0x10200000
            context.startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(context, "无法启动助手: " + e.message, Toast.LENGTH_SHORT).show()
        }
    }


}
